package com.tpyule.tpclass.web.Controller;

import com.tpyule.tpclass.entity.bean.FailResultBean;
import com.tpyule.tpclass.entity.bean.ResultBean;
import com.tpyule.tpclass.entity.bean.SuccessResultBean;
import com.tpyule.tpclass.entity.pojo.Studied;
import com.tpyule.tpclass.service.StudiedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zzz
 * @version 1.0
 * @date 2020/4/16 23:24
 */
@RestController
@RequestMapping("/studied")
public class StudiedControler extends BaseController{
    @Autowired
    StudiedService studiedService;
    @RequestMapping("/studySection")
    @ResponseBody
    public void studySection(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultBean resultBean = null;
        String courseId = request.getParameter("courseId");
        String sectionId = request.getParameter("sectionId");
        String userId = request.getParameter("userId");
        if(courseId==null || "".equals(courseId) || sectionId == null || "".equals(sectionId) || userId == null || "".equals(userId)) {
            resultBean = new FailResultBean("数据错误");
        } else {
            Studied studied = studiedService.getLastStudied(userId,courseId);
            if (studied==null||studied.getSectionId() != sectionId){
                studied.setState(1);
                int result = studiedService.updateStudied(studied);
                // 判断是否存在
                Studied sStudied = studiedService.getStudiedBySU(userId,sectionId);
                if (sStudied!=null){
                    sStudied.setState(0);
                    studiedService.updateStudied(sStudied);
                } else {
                    Studied newStudied = new Studied();
                    newStudied.setCourseId(courseId);
                    newStudied.setSectionId(sectionId);
                    newStudied.setUserId(userId);
                    studiedService.addStudied(newStudied);
                }
            }
            resultBean = new SuccessResultBean("成功");
        }
        this.setAjaxResponseResult(response,resultBean);
    }
}
